package com.patMall.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.patMall.entity.*;
import com.patMall.service.*;
import io.swagger.models.auth.In;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 750909637@qq.com
 * @PackageName patMall
 * @Package com.patMall.controller
 * @Date 2024/1/10 15:07
 * @Version 1.0
 */
@Controller
@RequestMapping("commodity")
public class CommodityController {
    @Resource
    private CommodityService commodityService;

    @Resource
    private UserService userService;

    @Resource
    private UserAddressService userAddressService;

    @Resource
    private CommodityImgService commodityImgService;
@Resource
private StoreService storeService;
    @PostMapping("findAllCommodity")
    @ResponseBody
    public Object findAllCommodity(){
        List<Commodity> commodityList = commodityService.selectAllByCommodity(1);
        Map map = new HashMap();
        if (commodityList.size() > 0) {
            map.put("data", commodityList);
            map.put("msg", "success");
        }else {
            map.put("msg","NoFound");
        }
        return map;
    }
    @PostMapping("getCommodityId")
    @ResponseBody
    public Object getCommodityId(Integer commodityId){
        Commodity commodity = commodityService.getCommodityId(commodityId);
        Map map = new HashMap();
        if (commodity != null) {
            map.put("data", commodity);
            map.put("msg", "success");
        }else {
            map.put("msg","NoFound");
        }
        return map;
    }
    @PostMapping("getBuyCommodityId")
    @ResponseBody
    public Object getBuyCommodityId(Integer commodityId,Integer userId){
        Commodity commodity = commodityService.getCommodityId(commodityId);
        Store store = storeService.getStoreId(commodity.getCommodityStoreId());
        commodity.setStore(store);
        User user = userService.getUserId(userId);
        List<UserAddress> userAddressList = userAddressService.selectAddressByUserId(user.getUserId());
        user.setUserAddressList(userAddressList);
        Map map = new HashMap();
        if (commodity != null && user != null) {
            map.put("data", commodity);
            map.put("address", user);
            map.put("msg", "success");
        }else{
            map.put("msg","fail");
        }
        return map;
    }
    @PostMapping("addNumberOfViews")
    @ResponseBody
    public void addNumberOfViews(Integer commodityId){
        Commodity commodityNum = commodityService.getCommodityId(commodityId);
        Commodity commodity = new Commodity();
        commodity.setCommodityId(commodityNum.getCommodityId());
        commodity.setNumberOfViews(commodityNum.getNumberOfViews()+1);
        commodityService.updateCommodity(commodity);
    }

    @PostMapping("searchCommodity")
    @ResponseBody
    public Object searchCommodity(Commodity commodity){
        List<Commodity> commodityList = commodityService.searchCommodity(commodity);
        Map map = new HashMap();
        if (commodityList.size() > 0) {
            map.put("data", commodityList);
            map.put("msg", "success");
        }else {
            map.put("msg","NoFound");
        }
        return map;
    }
    @PostMapping("getStoreCommodityAll")
    @ResponseBody
    public Object getStoreCommodityAll(Integer storeId,String sorting_p,String sorting_t){
        int sorting_p1 = 1;
        if (sorting_p == "降序"){
            sorting_p1 = 1;
        }else if (sorting_p == "升序"){
            sorting_p1 = 2;
        }
        int sorting_t1 = 1;
        if (sorting_t == "最新"){
            sorting_t1 = 1;
        }else if (sorting_t == "以前"){
            sorting_t1 = 2;
        }
        List<Commodity> commodityList = commodityService.getStoreCommodityAll(storeId,sorting_p1,sorting_t1);
        Map map = new HashMap();
        if (commodityList.size() > 0) {
            map.put("data", commodityList);
            map.put("msg", "success");
        }else {
            map.put("msg","fail");
        }
        return map;
    }
    @PostMapping("getStoreCommodity")
    @ResponseBody
    public Object getStoreCommodity(){
        List<Commodity> commodityList = commodityService.getStoreCommodity();
        Map map = new HashMap();
        if (commodityList.size() > 0) {
            map.put("data", commodityList);
            map.put("msg", "success");
        }else {
            map.put("msg","fail");
        }
        return map;
    }



    @PostMapping("addCommodity")
    @ResponseBody
    public Object addCommodity(Commodity commodity,@RequestParam("files[]") MultipartFile[] files) {
        Map map = new HashMap();
        CommodityImg commodityImg = new CommodityImg();
        int count = commodityService.addCommodity(commodity);
        if (count == 1) {
            Commodity commodity1 = commodityService.getCommodityByCommodityId(commodity);
            commodityImg.setCommodityId(commodity1.getCommodityId());
            map.put("code",0);
            for (MultipartFile file : files) {
                // 默认成功
                map.put("code", 0);
                // 假设0表示成功
                if (file != null && file.getContentType().startsWith("image/")) {
                    String originalFilename = file.getOriginalFilename();
                    String fileExtension = FilenameUtils.getExtension(originalFilename);
                    // 获取文件扩展名
                    if (!"jpg".equalsIgnoreCase(fileExtension) && !"png".equalsIgnoreCase(fileExtension)) {
                        continue;
                        // 不是有效的图像文件，跳过
                    }
                    String baseDir = "P:/pat_mall/commodityImg/";
                    System.err.println(baseDir);
                    String subDir = commodity1.getCommodityId() + "_" + commodity.getCommodityStoreId() + "_" + commodity.getCommodityName() + "_commentImg/";
                    File subDirFile = new File(baseDir, subDir);
                    if (!subDirFile.exists()) {
                        subDirFile.mkdirs();
                        // 确保子目录存在
                    }

                    // 使用UUID作为文件名的一部分来避免冲突
                    String newFileName = System.currentTimeMillis() + "_" + originalFilename;
                    String savePath = baseDir + subDir + newFileName;
                    System.err.println(savePath);
                    try {
                        // 真实路径
                        file.transferTo(new File(savePath));
                        // 设置访问路径
                        commodityImg.setCommodityImg("pat_mall/commodityImg/" + subDir + "/" + newFileName);
                    } catch (IOException e) {
                        map.put("code", 1);
                        // 提供错误信息
                        e.printStackTrace();
                    }
                }
                int row = commodityImgService.addCommodityImg(commodityImg);
                if (row == 1) {
                    map.put("code", 0);
                    continue;
                } else {
                    map.put("code", 1);
                    break;
                }
            }
        }else {
            map.put("code", 1);
        }
        return map;
    }
    @PostMapping("selectAllCommodity")
    @ResponseBody
    public Object selectAllCommodity(int page,int limit){
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Commodity> commodityList = commodityService.selectAllCommodity();
        Page<Commodity> pageList = (Page<Commodity>) commodityList;
        long count = pageList.toPageInfo().getTotal();
        map.put("code",0);
        map.put("msg", "这是数据传来的！");
        map.put("count", count);
        map.put("data", pageList);
        return map;
    }
    @PostMapping("updateCommodity")
    @ResponseBody
    public String updateCommodity(Commodity commodity){
        int count = commodityService.updateCommodity(commodity);
        if (count == 1){
            return "success";
        }else {
            return "fail";
        }
    }
    @PostMapping("getAllByCommodityName")
    @ResponseBody
    public Object getAllByCommodityName(int page,int limit,String commodityName){
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Commodity> commodityList = commodityService.getAllByCommodityName(commodityName);
        Page<Commodity> pageList = (Page<Commodity>) commodityList;
        long count = pageList.toPageInfo().getTotal();
        map.put("code",0);
        map.put("msg", "这是数据传来的！");
        map.put("count", count);
        map.put("data", pageList);
        return map;
    }
}
